import re
import os
import jieba

from backend.services.product_service import ProductService
from backend.services.order_service import OrderService

# 获取当前文件所在目录，拼接词典路径（避免相对路径错误）
current_dir = os.path.dirname(os.path.abspath(__file__))
custom_dict_path = os.path.join(current_dir, 'custom_dict.txt')
jieba.load_userdict(custom_dict_path)  # 显式加载词典
class EntityExtractor:
    def __init__(self):
        self.product_service = ProductService()
        self.order_service = OrderService()

        # 正则模式
        self.patterns = {
            'product_id': re.compile(r'[Pp]\d{3}|[产品|商品|货号]\s*([A-Z]\d+)'),
            'order_id': re.compile(r'[Oo][Rr][Dd]\d{3}|订单[：:]*\s*([A-Z]{3}\d+)'),
            'human_service': re.compile(r'(人工|客服|真人|转人工|人工服务|找客服)'),
            'price_query': re.compile(r'价格|多少钱|售价|价位|报价|什么价|优惠价|价'),
            'effect_query': re.compile(r'功效|效果|作用|用途|功能|能改善|能保湿'),
            'usage_query': re.compile(r'用法|使用|操作|步骤|怎么用|用几次|哪一步'),
            'skin_type_query': re.compile(r'肤质|皮肤|油皮|干皮|敏感肌|混合肌|适合什么肤质|能用吗'),
            'series_query': re.compile(r'系列|产品线|多元优效|特安修护|净肌平衡|属于哪个系列'),
            'after_sales': re.compile(r'退货|换货|售后|退款|变质|破损|问题|退掉|换新'),
            'address': re.compile(r'修改地址|更新地址|改地址|地址变更|配送地址|收货信息|地址修改|换地址|地址错了|地址不对|改收货')
        }

    def extract_entities(self, text):
        """从文本中抽取实体"""
        entities = {
            "product_id": None,
            "product_name": None,
            "order_id": None,
            "human_service": False,
            "price_query": False,
            "effect_query": False,
            "usage_query": False,
            "skin_type_query": False,
            "series_query": False,
            "after_sales": False,
            "address": False
        }

        # 检查所有模式
        for entity_type, pattern in self.patterns.items():
            if pattern.search(text):
                if entity_type in ['product_id', 'order_id']:
                    match = pattern.search(text)
                    entities[entity_type] = match.group(1) if match.lastindex else match.group()
                else:
                    entities[entity_type] = True

        # 增强产品名称识别
        if not entities["product_id"] and not entities["product_name"]:
            words = jieba.lcut(text)
            product_keywords = {"净肌平衡", "清透水", "特安修护", "多元优效", "乳液", "面霜", "精华", "面膜"}
            product_name_candidates = [word for word in words if word in product_keywords]

            if product_name_candidates:
                candidates_text = " ".join(product_name_candidates)
                products = self.product_service.fuzzy_search_products(candidates_text)
                if products:
                    entities["product_name"] = products[0]["name"]

        return entities